"""
配置虚拟音频设备
实现本地静音，但直播间有声音
"""
import os
import sys
from pathlib import Path

def list_audio_devices():
    """列出所有可用的音频设备"""
    print("=" * 70)
    print("检测可用的音频设备")
    print("=" * 70)
    
    try:
        import pygame
        pygame.mixer.init()
        
        # 获取所有音频设备
        devices = []
        try:
            # pygame 2.0+ 支持获取设备列表
            import pygame._sdl2.audio as sdl2_audio
            devices = sdl2_audio.get_audio_device_names(False)  # False = 输出设备
        except:
            print("⚠️ 当前pygame版本不支持列出设备，请手动配置")
            print("   推荐安装: pip install pygame>=2.0.0")
            return []
        
        pygame.mixer.quit()
        
        if devices:
            print(f"\n找到 {len(devices)} 个音频输出设备:\n")
            for i, device in enumerate(devices):
                print(f"  [{i}] {device}")
                if 'CABLE' in device.upper() or 'VIRTUAL' in device.upper():
                    print(f"      ⭐ 虚拟音频设备（推荐用于直播）")
            return devices
        else:
            print("❌ 未找到音频设备")
            return []
            
    except Exception as e:
        print(f"❌ 检测音频设备失败: {e}")
        return []

def configure_virtual_audio():
    """配置虚拟音频设备"""
    print("\n" + "=" * 70)
    print("虚拟音频配置向导")
    print("=" * 70)
    print("\n目标: 实现本地静音，但直播间有声音\n")
    
    # 列出设备
    devices = list_audio_devices()
    
    if not devices:
        print("\n⚠️ 请先安装虚拟音频设备:")
        print("   1. VB-AUDIO Virtual Cable: https://vb-audio.com/Cable/")
        print("   2. 或 VoiceMeeter: https://vb-audio.com/Voicemeeter/")
        print("\n安装完成后重启电脑，再次运行此脚本")
        return
    
    # 查找虚拟音频设备
    virtual_devices = []
    for i, device in enumerate(devices):
        if 'CABLE' in device.upper() or 'VIRTUAL' in device.upper() or 'VOICEMEETER' in device.upper():
            virtual_devices.append((i, device))
    
    if not virtual_devices:
        print("\n⚠️ 未检测到虚拟音频设备")
        print("\n请选择一个音频设备作为输出:")
        try:
            choice = int(input(f"请输入设备编号 (0-{len(devices)-1}): "))
            if 0 <= choice < len(devices):
                selected_device = devices[choice]
            else:
                print("❌ 无效的设备编号")
                return
        except:
            print("❌ 输入错误")
            return
    else:
        print("\n✓ 检测到虚拟音频设备:\n")
        for i, device in virtual_devices:
            print(f"  [{i}] {device}")
        
        if len(virtual_devices) == 1:
            selected_device = virtual_devices[0][1]
            print(f"\n自动选择: {selected_device}")
        else:
            try:
                choice = int(input(f"\n请选择虚拟音频设备编号: "))
                selected_device = devices[choice]
            except:
                selected_device = virtual_devices[0][1]
                print(f"使用默认设备: {selected_device}")
    
    # 设置环境变量
    print("\n" + "=" * 70)
    print("配置环境变量")
    print("=" * 70)
    
    env_file = Path(__file__).parent / "config" / ".env"
    
    try:
        # 读取现有配置
        env_content = ""
        if env_file.exists():
            with open(env_file, 'r', encoding='utf-8') as f:
                env_content = f.read()
        
        # 更新或添加虚拟音频设备配置
        if 'VIRTUAL_AUDIO_DEVICE=' in env_content:
            # 更新现有配置
            lines = env_content.split('\n')
            new_lines = []
            for line in lines:
                if line.startswith('VIRTUAL_AUDIO_DEVICE='):
                    new_lines.append(f'VIRTUAL_AUDIO_DEVICE={selected_device}')
                else:
                    new_lines.append(line)
            env_content = '\n'.join(new_lines)
        else:
            # 添加新配置
            if env_content and not env_content.endswith('\n'):
                env_content += '\n'
            env_content += f'\n# 虚拟音频设备配置（实现本地静音但直播有声）\n'
            env_content += f'VIRTUAL_AUDIO_DEVICE={selected_device}\n'
        
        # 写入配置
        with open(env_file, 'w', encoding='utf-8') as f:
            f.write(env_content)
        
        print(f"\n✓ 配置已保存到: {env_file}")
        print(f"  虚拟音频设备: {selected_device}")
        
    except Exception as e:
        print(f"\n❌ 保存配置失败: {e}")
        print(f"\n请手动添加到 {env_file}:")
        print(f"  VIRTUAL_AUDIO_DEVICE={selected_device}")
        return
    
    # 输出OBS配置说明
    print("\n" + "=" * 70)
    print("OBS配置说明")
    print("=" * 70)
    print("\n1. 打开OBS")
    print("2. 添加音频源:")
    print("   - 来源 → 添加 → 音频输入捕获")
    print(f"   - 设备选择: {selected_device}")
    print("3. 调整音量混音器")
    print("4. 本地扬声器静音，OBS推流有声音 ✓")
    
    print("\n" + "=" * 70)
    print("测试配置")
    print("=" * 70)
    print("\n运行以下命令测试:")
    print("  python test_volcengine_fixed.py")
    print("\n预期效果:")
    print("  ✓ 本地扬声器静音（听不到声音）")
    print("  ✓ OBS音频混音器有波动（推流有声音）")
    print("=" * 70)

if __name__ == "__main__":
    try:
        configure_virtual_audio()
    except KeyboardInterrupt:
        print("\n\n配置已取消")
    except Exception as e:
        print(f"\n配置失败: {e}")
        import traceback
        traceback.print_exc()
